/**
 * Created by lihao on 15/10/27.
 */
require(['jquery', 'hxz', 'morris', 'alertify', 'select2'], function ($, hxz, Morris, alertify, select2) {

  function fetchAccountList() {
    var accountList = "/account/list";
    hxz.doPost({url: accountList}, function (data) {
      if (data.status == "0") {
        return alertify.log("系统错误");
      }
      render(data.data);
    });
  }

  function render(dataList, page, count) {

    var tpl = _.template($('#tpl-account-list-item').html());
    $("#account-list-body").html("");
    for (var i = 0; i < dataList.length; i++) {
      var _data = dataList[i];
      _data.datetime = hxz.datetime;
      _data.accountType = function (data) {
        if(data == "1")
            return "华为网盘";
        else if(data == "2")
            return "新浪微盘";
      }
      $("#account-list-body").append(tpl(_data));
    }
  };

  function event() {
    $("#account-list-body").on("click", ".btn-delete", function () {
      var cloudId = $(this).attr("data-id");
      alertify.confirm('确定移除该账号吗？', function (event) {
        // 点击确认
        if (event) {
          hxz.doPost({url: "/account/delete", data:{"cloudId":cloudId}}, function (data) {
            if (data.status == "0") {
              return alertify.log("系统错误");
            } else {
              alertify.log("删除成功");
              setTimeout("window.location.reload()", 1000);
            }
          });
        }
      });
    });

    $("#btn-add").click(function () {
      $("#editType").val("0");
      $("#account-insert").modal("show");
    });

    $(".btn-edit").click(function () {
      $("#editType").val("1");
      $("#cloudId").val($(this).attr("data-id"));
      $("#account-insert").modal("show");
    });
    
    $("#insert-submit").click(function () {
      var editType = $("#editType").val();
      var account = $("#account").val();
      var password = $("#password").val();
      var cloudType = $("#cloudType").val();
      var data;
      if(editType == "0") {
        data = {
          "account" : account,
          "password" : password,
          "editType" : editType,
          "cloudType" : cloudType
        }
      } else {
        var cloudId = $("#cloudId").val();
        data = {
          "account" : account,
          "password" : password,
          "editType" : editType,
          "cloudType" : cloudType,
          "cloudId" : cloudId
        }
      }
      hxz.doPost({url: "/account/add", data:data}, function (data) {
        if (data.status == "0") {
          return alertify.log("系统错误");
        } else {
          alertify.log("编辑成功");
          setTimeout("window.location.reload()", 1000);
        }
      });
    })
  }

  function pageInit() {
    fetchAccountList();
    event();
  }

  // 执行初始化
  pageInit();
});